﻿using Choucius.Boilerplate9.Controllers;
using Choucius.Boilerplate9.DtoBase.MES;
using Choucius.Boilerplate9.OutboundTasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Choucius.Boilerplate9.Web.Controllers
{
    public class OutboundTasksController : Boilerplate9ControllerBase
    {
        //private readonly IMesApiClient _mesApiClient;
        //public OutboundTasksController(IMesApiClient mesApiClient)
        //{
        //    _mesApiClient = mesApiClient;
        //}
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly ILogger<OutboundTasksController> _logger;
        private readonly IOutboundTaskAppService _outboundTaskAppService;

        public OutboundTasksController(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        public OutboundTasksController(IHttpClientFactory httpClientFactory, ILogger<OutboundTasksController> logger, IOutboundTaskAppService outboundTaskAppService) : this(httpClientFactory)
        {
            _logger = logger;
            _outboundTaskAppService = outboundTaskAppService;
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public async Task<ActionResult> GetOutboundTaskAsync()
        {
            // 调用MES接口
            //var result = await _mesApiClient.PostAsync("http://192.168.9.88:9002/Frame/SqlData?cmdname=selectZSPlan", "");
            string url = "http://192.168.9.88:9002/Frame/SqlData?cmdname=selectZSPlan";
            string responseBody = string.Empty;
            using (var httpClient = _httpClientFactory.CreateClient())
            {
                var content = new StringContent(string.Empty, Encoding.UTF8, "application/json");
                var response = await httpClient.PostAsync(url, content);
                if (response.IsSuccessStatusCode)
                {
                    responseBody = await response.Content.ReadAsStringAsync();
                    _logger.LogInformation(responseBody);
                }
                else if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    _logger.LogError($"{response.StatusCode}: Resource not found.");
                }
                else if (response.StatusCode == HttpStatusCode.InternalServerError)
                {
                    _logger.LogError($"{response.StatusCode}: Internal server error.");
                }
                else
                {
                    // 你可以根据需要添加更多的状态码检查
                    _logger.LogError(response.StatusCode.ToString());
                }
                //response.EnsureSuccessStatusCode();
            }
            if (!string.IsNullOrEmpty(responseBody))
            {
                // 反序列化Json
                MesDto dto = JsonSerializer.Deserialize<MesDto>(responseBody);
                // TODO: 创建明日出库任务
                _ = _outboundTaskAppService.CreateOutboundTaskFromMesAsync(dto.data.ds);
            }
            return View("Index"); // 返回相同的视图，或者重定向到其他页面
        }
    }
}
